package dth.bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.primefaces.event.FileUploadEvent;

import dth.dao.MovieDAO;
import dth.entity.Account;
import dth.entity.Movie;
import dth.entity.SetupBox;
import dth.utils.DthUtil;
import antlr.collections.List;

@ManagedBean(name = "movieBean")
public class MovieBean {
	private int id;// use to insert delete
	private String name;
	private double price;
	private Date date;
	private int fkAdminId;
	private String image;
	private String fileName;
	private String des;
	private String quantity;
	private String imageOld;

	public String getImageOld() {
		return imageOld;
	}

	public void setImageOld(String imageOld) {
		this.imageOld = imageOld;
	}

	public String getQuantity() {
		return quantity;
	}

	public void setQuantity(String quantity) {
		this.quantity = quantity;
	}

	public String getDes() {
		return des;
	}

	public void setDes(String des) {
		this.des = des;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getImage() {
		return image;
	}

	public void setImage(String image) {
		this.image = image;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public int getFkAdminId() {
		return fkAdminId;
	}

	public void setFkAdminId(int fkAdminId) {
		this.fkAdminId = fkAdminId;
	}

	public MovieBean() {
		System.out.println("---request url:" + DthUtil.getRequestURL());
		if (DthUtil.getRequestURL().contains("movie.xhtml")) {
			System.out.println("--vao day role:" + LoginBean.roleCode);
			if (LoginBean.roleCode != 1)
				DthUtil.navigateTo("welcome.xhtml");
		}

		System.out.println("--movie bean");
		Object objectAction = DthUtil.getRequest().getParameter("action");
		System.out.println("----------action:" + objectAction);
		if (objectAction != null) {
			if (objectAction.equals("insert")) {
				String image = DthUtil.getRequest().getParameter("imageI");
				this.fileName = image;
			}
			if (objectAction.equals("delete")) {
				Object objectId = DthUtil.getRequest().getParameter("movie_id");
				String image = DthUtil.getRequest().getParameter("movie_image");
				this.image = image;
				if (objectId != null)
					id = Integer.parseInt(objectId.toString());
				System.out.println("---id delete:" + id);
			} else if (objectAction.equals("update")) {
				Object objectId = DthUtil.getRequest().getParameter("movie_id");
				if (objectId != null)
					id = Integer.parseInt(objectId.toString());
				System.out.println("---id edit:" + id);
				for (Movie movie : getListMovie()) {
					if (movie.getMovieId() == id) {
						this.name = movie.getMovieName();
						this.price = movie.getMoviePrice();
						this.fkAdminId = movie.getFkAdminId();
						this.des = movie.getDescription();
						this.image = movie.getImage();
						this.fileName = image;
						this.imageOld = image;
					}
				}
				System.out.println("-----update movie name:" + name);
			}
		}
	}

	public java.util.List<Movie> getListMovie() {
		MovieDAO movieDAO = new MovieDAO();
		return movieDAO.getListMovie();
	}

	public void delete() {
		try {
			MovieDAO movieDAO = new MovieDAO();
			int count = movieDAO.delete(id);
			if (count > 0)
				DthUtil.showMessage("Thông báo", "Đã xóa thành công");
			else
				DthUtil.showMessage("Thông báo", "Đã xóa thất bại");
		} catch (Exception ex) {
			DthUtil.showMessage("Thông báo", "Có lỗi khi xóa");
		}
		System.out.println("delete img movie: " + image);
		delImg(image);
	}

	public void insert() {
		System.out.println("---id=" + id + "action = insert");

		try {
			System.out.println("iimmmmmmmmmmmmmm" + imageOld);
			System.out.println("---id=" + id);
			String filename = DthUtil.getRequest().getParameter("filename");

			MovieDAO movieDAO = new MovieDAO();
			Movie movie1 = new Movie();
			movie1.setMovieId(id);
			movie1.setMoviePrice(price);
			movie1.setMovieName(name);
			// movie1.setMovieTime(date);
			movie1.setImage(filename);
			movie1.setDescription(des);
			Account ac = DthUtil.getAccountDTH();
			movie1.setFkAdminId(ac.getFkAdminId());
			java.util.Date date = new java.util.Date();// lay ngay hien tai
			movie1.setDateInsert(new Date(date.getTime()));
			System.out.println(filename);
			int count = 0;
			if (id == 0) {
				System.out.println("MovieBean insert: namemovie= " + name
						+ " img= " + filename + " des= " + des);
				count = movieDAO.insert(movie1);
				if (count > 0)
					DthUtil.showMessage("Thông báo", "Đã insert thành công");
				else
					DthUtil.showMessage("Thông báo", "Đã insert thất bại");
			} else if (id != 0) {
				System.out.println("MovieBean update: namemovie= " + name
						+ " img= " + filename + "des= " + des + " id: " + id);
				count = movieDAO.update(movie1);
				if (count > 0) {
					if(!imageOld.equals(filename))
					{
						delImg(imageOld);
					}
					
					
					DthUtil.showMessage("Thông báo", "Đã update thành công");
				} else
					DthUtil.showMessage("Thông báo", "Đã update thất bại");

			}

		} catch (Exception ex) {
			System.out.println("---------error:" + ex.getMessage());
			DthUtil.showMessage("Thông báo", "Đã insert thất bại");
		}
	}

	public void upload(FileUploadEvent event) {
		// Do what you want with the file
		ExternalContext extContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		try {
			this.image = event.getFile().getFileName();
			copyFile(event.getFile().getFileName(), event.getFile()
					.getInputstream());
			FacesMessage msg = new FacesMessage("Success! ", event.getFile()
					.getFileName() + " is uploaded.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void copyFile(String fileName, InputStream in) {
		try {

			// write the inputStream to a FileOutputStream

			ExternalContext extContext = FacesContext.getCurrentInstance()
					.getExternalContext();
			OutputStream out = new FileOutputStream(new File(
					extContext.getRealPath("//images//" + fileName)));
			this.fileName = fileName;
			System.out.println(extContext.getRealPath("//images//"));

			// OutputStream out = new FileOutputStream(new File(destination
			// + fileName));
			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			in.close();
			out.flush();
			out.close();

			System.out.println("New file created!");
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	public void delImg(String name) {

		System.out.println("deleteeeeeeeeeee0 " + name);
		ExternalContext extContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		File deleteFile = new File(extContext.getRealPath("//images//" + name));
		deleteFile.delete();
	}

	public void delImg2() {
		System.out.println("dellllllleete");
		if (!fileName.equals("movieico.png")) {
			System.out.println("deleteeeeeeeeeee2 " + fileName);
			ExternalContext extContext = FacesContext.getCurrentInstance()
					.getExternalContext();
			File deleteFile = new File(extContext.getRealPath("//images//"
					+ fileName));
			deleteFile.delete();
		}
	}
	public void delImg1() {
		for (Movie mo : getListMovie()) {
			if (mo.getMovieId() == id) {
				if (!image.trim().equals(mo.getImage().trim())) {
					System.out.println("deleteeeeeeeeeee1 " + image + "id "
							+ id);
					ExternalContext extContext = FacesContext
							.getCurrentInstance().getExternalContext();
					File deleteFile = new File(
							extContext.getRealPath("//images//" + image));
					deleteFile.delete();
				}
			}
		}
	}
}
